<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" size="small">
        <el-form-item>
          <el-input
            v-model="listQuery.name"
            placeholder="请输入内容"
            clearable
            @keyup.enter.native="handleFilter"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click.native="handleFilter"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        size="small"
        v-loading="listLoading"
        highlight-current-row
        style="width: 80%"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          align="left"
          label="案由名称"
          prop="name"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getReasons"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="600">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="案由名称" prop="name">
          <el-input v-model="form.name" placeholder="案由名称" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getReasonList, addReason, updateReason, delReason } from "@/api/case";
import Pagination from "@/components/Pagination";
const defaultForm = {
  id: null,
  name: "",
};

export default {
  name: "Reason",
  components: {
    Pagination,
  },
  computed: {
    getTitle() {
      return this.dialogType === "edit"
        ? `编辑${this.title}`
        : `新增${this.title}`;
    },
  },
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        name: [{ required: true, message: "请输入案由", trigger: "blur" }],
      },

      title: "案由",
      dialogVisible: false,
      dialogType: "new",
      dataList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 10,
        name: null,
      },
    };
  },

  created() {
    this.getReasons();
  },
  methods: {
    getReasons() {
      this.listLoading = true;
      getReasonList(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.dataList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取案由数据失败");
          this.listLoading = false;
        });
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getReasons();
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    //
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    //
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该信息吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delReason(row.id);

          this.dataList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        if (isEdit) {
          const res = await updateReason(this.form);
          const index = this.dataList.findIndex((v) => v.id === res.id);
          this.dataList.splice(index, 1, res);
        } else {
          const res = await addReason(this.form);
          const { id } = res;
          if (id > 0) {
            this.getReasons();
          }
        }

        const { name } = this.form;
        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>案由: ${name}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
</style>